//
//  ZBCheckAlasset.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/12/18.
//  Copyright © 2015年 szb. All rights reserved.
//

#import "ZBCheckAlasset.h"
#import "UIImageView+WebCache.h"
#import "BPhttpTool.h"
#import "QiniuSDK.h"
#import "AccountTool.h"
#import "BPhttpTool.h"
#import "ZBpostModel.h"

@implementation ZBCheckAlasset

- (void)checkAlaaserArry:(NSArray *)arry withView:(UIView *)view
{
    _loadHud = [MBProgressHUD showMessage:@"稍后为您支付~" toView:view];
    _loadHud.userInteractionEnabled = NO;
    
    NSLog(@"正在努力上传的 图片的 array = %@", arry);
    
    NSMutableArray *firstArry = [NSMutableArray array];
    //去除重复的照片
    for (ALAsset *asset in arry) {
        NSURL *assetUrlStr = [asset defaultRepresentation].url;
        if ([firstArry containsObject:assetUrlStr] == NO) {
            [firstArry addObject:assetUrlStr];
        }
    }
    //已经上传过的无需再次上传
    [self checkHavePost:firstArry];
}

- (void)checkHavePost:(NSMutableArray *)assetUrlArry
{
    NSMutableArray *arry = [NSMutableArray array];
    NSMutableArray *keyArry = [NSMutableArray array];
    NSInteger index = assetUrlArry.count;
    for (NSURL *assetUrl in assetUrlArry) {
        
        NSString *imageKey = [assetUrl absoluteString];
        NSRange range = [imageKey rangeOfString:@"id="];
        imageKey = [imageKey substringFromIndex:range.location];
        imageKey = [imageKey stringByReplacingOccurrencesOfString:@"-" withString:@""];
        imageKey = [imageKey substringWithRange:NSMakeRange(3, 28)];
        [keyArry addObject:imageKey];
        
        NSURL *imageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",pictureUrl,imageKey,ThumbPicture]];
        
        [BPhttpTool get:[imageUrl absoluteString] params:nil success:^(id responseObj) {
        } failure:^(NSError *error) {
            if (error.code == -1016) {
                [keyArry removeObject:imageKey];
                [assetUrlArry removeObject:assetUrl];
            }
            [arry addObject:error];
            if (arry.count == index) {
                [self urlToAlasset:assetUrlArry add:keyArry];
            }
        }];
    }
}
//将url转换为alasset格式，并设置上传七牛的key
- (void)urlToAlasset:(NSMutableArray *)urlArry add:(NSMutableArray *)keyArry
{
    //说明都已经上传过了
    if (urlArry.count > 0) {
        NSMutableArray * secondArry = [NSMutableArray array];
        static dispatch_once_t pred = 0;
        static ALAssetsLibrary *library = nil;
        dispatch_once(&pred,
                      ^{
                          library = [[ALAssetsLibrary alloc] init];
                      });
        
        for (NSURL *url in urlArry) {
            [library assetForURL:url resultBlock:^(ALAsset *asset) {
                [secondArry addObject:asset];
                
                if (secondArry.count == urlArry.count) {
                    //上传照片
                    [self postToQiniuAlassetArry:secondArry withAssetKey:keyArry];
                    _dismissBlock();
                }
                
            } failureBlock:^(NSError *error) {
                BPLog(@"转照片失败");
            }];
        }
    }
    //都已经上传
    else{
        _ZBblock();
        [_loadHud hide:YES];
        _dismissBlock();
    }
    
}

- (void)postToQiniuAlassetArry:(NSMutableArray *)alassetArry withAssetKey:(NSMutableArray *)assetKey
{
    //1.将需要上传的作品保存到数据库
    NSMutableArray *unpostArry = [NSMutableArray array];
    _posetManger = [[CoreDateManager alloc] init];
    for (int i = 0; i < alassetArry.count; i++) {
        ZBpostModel *model = [[ZBpostModel alloc] init];
        model.imageKey = assetKey[i];
        ALAsset *asset = alassetArry[i];
        model.imageStr = [[asset defaultRepresentation].url absoluteString];
        [unpostArry addObject:model];
    }
    [_posetManger insertUnpostImage:unpostArry];
    
    //2.获取七牛的token用于上传作品
    [BPhttpTool get:[NSString stringWithFormat:@"%@Upload/get_qiniu_token",BPhttp] params:nil success:^(id responseObj) {
        NSString *token = [responseObj valueForKey:@"token"];
        QNUploadManager *uploadManager = [[QNUploadManager alloc] init];
        QNUploadOption *opt = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
            _loadHud.mode = MBProgressHUDModeDeterminate;
            if (key == [assetKey lastObject]) {
                _loadHud.progress = percent;
            }
        }];
        //3.将所有需要上传的照片上传
        NSMutableArray *arry = [NSMutableArray array];
        for (int i = 0; i < assetKey.count; i++) {
            [uploadManager putALAsset:alassetArry[i] key:assetKey[i] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                if (info.statusCode == 200 && resp){
                    [arry addObject:key];
                    [_posetManger deleteUnpostInfo:key];
                    if (arry.count == alassetArry.count) {
                        [_loadHud hide:YES afterDelay:0.3];
                        _ZBblock();
                    }
                }else{
                    
                }
            } option:opt];
        }
        
    } failure:^(NSError *error) {
        _loadHud.mode = MBProgressHUDModeCustomView;
        _loadHud.labelText = @"上传图片失败";
        [_loadHud hide:YES afterDelay:0.7];
    }];
}

- (void)checkAlaaserArry2:(NSArray *)arry withView:(UIView *)view
{
    NSMutableArray *firstArry = [NSMutableArray array];
    //去除重复的照片
    for (NSString *assetStr in arry) {
        NSURL *assetUrlStr = [NSURL URLWithString:assetStr];
        if ([firstArry containsObject:assetUrlStr] == NO) {
            [firstArry addObject:assetUrlStr];
        }
    }
    //已经上传过的无需再次上传
    [self checkHavePost2:firstArry];
}

- (void)checkHavePost2:(NSMutableArray *)assetUrlArry
{
    NSMutableArray *arry = [NSMutableArray array];
    NSMutableArray *keyArry = [NSMutableArray array];
    NSInteger index = assetUrlArry.count;
    for (NSURL *assetUrl in assetUrlArry) {
        
        NSString *imageKey = [assetUrl absoluteString];
        NSRange range = [imageKey rangeOfString:@"id="];
        imageKey = [imageKey substringFromIndex:range.location];
        imageKey = [imageKey stringByReplacingOccurrencesOfString:@"-" withString:@""];
        imageKey = [imageKey substringWithRange:NSMakeRange(3, 28)];
        [keyArry addObject:imageKey];
        
        NSURL *imageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",pictureUrl,imageKey,ThumbPicture]];
        
        [BPhttpTool get:[imageUrl absoluteString] params:nil success:^(id responseObj) {
        } failure:^(NSError *error) {
            if (error.code == -1016) {
                [keyArry removeObject:imageKey];
                [assetUrlArry removeObject:assetUrl];
            }
            [arry addObject:error];
            if (arry.count == index) {
                [self urlToAlasset2:assetUrlArry add:keyArry];
            }
        }];
    }
}

- (void)urlToAlasset2:(NSMutableArray *)urlArry add:(NSMutableArray *)keyArry
{
    NSLog(@"%@",urlArry);
    if (_posetManger == nil) {
        _posetManger = [[CoreDateManager alloc] init];
    }
    //说明都已经上传过了
    if (urlArry.count > 0) {
        static dispatch_once_t pred = 0;
        static ALAssetsLibrary *library = nil;
        dispatch_once(&pred,
                      ^{
                          library = [[ALAssetsLibrary alloc] init];
                      });
        
        for (int i = 0; i < urlArry.count; i ++) {
            [library assetForURL:urlArry[i] resultBlock:^(ALAsset *asset) {
                NSLog(@"%d",i);
                    //上传照片
                [self postToQiniuAlassetArry2:asset withAssetKey:keyArry[i]];
                
            } failureBlock:^(NSError *error) {
                [_posetManger deleteUnpostInfo:keyArry[i]];
                [keyArry removeObjectAtIndex:i];
                BPLog(@"转照片失败");
            }];
        }
    }
    //都已经上传
    else{
        [_posetManger deleteAllpost];
    }
    
}

- (void)postToQiniuAlassetArry2:(ALAsset *)alasset withAssetKey:(NSString *)assetKey
{
    [BPhttpTool get:[NSString stringWithFormat:@"%@Upload/get_qiniu_token",BPhttp] params:nil success:^(id responseObj) {
        NSString *token = [responseObj valueForKey:@"token"];
        QNUploadManager *uploadManager = [[QNUploadManager alloc] init];
            [uploadManager putALAsset:alasset key:assetKey token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                if (info.statusCode == 200 && resp){
                    NSLog(@"%@--------%@",assetKey,key);
                    [_posetManger deleteUnpostInfo:assetKey];
                }else{
                    
                }
            } option:nil];
        
    } failure:^(NSError *error) {

    }];
}

@end
